package edu.snake.implement.model.arena.iterator;

import edu.snake.core.model.arena.Arena;
import edu.snake.core.model.arena.Position;
import edu.snake.implement.model.arena.Direction;
import edu.snake.implement.model.arena.PositionFactory;

import java.util.Iterator;

import static edu.snake.implement.model.arena.PositionFactory.getNewPosition;


public class SnakeDeploymentArenaIterator implements Iterator<Position> {

    private Position position;
    private final Arena arena;
    private boolean nextPositionLeft;

    public SnakeDeploymentArenaIterator(Position position, Arena arena) {
        this.position = position;
        this.arena = arena;
        nextPositionLeft = true;
    }

    public boolean hasNext() {
        return !(position.getWidth() == 0 && position.getHeight() == 0)
                && !(position.getWidth() == (arena.getWidth() - 1) && position.getHeight() == (arena.getHeight() - 1));
    }

    @Override
    public Position next() {

        int width = position.getWidth();
        int height = position.getHeight();
        if (width == 0 && nextPositionLeft) {
            width = 0;
            height = height - 1;
            nextPositionLeft = false;
            position = getNewPosition(width, height);
            return position;
        } else if (width == arena.getWidth() - 1 && !nextPositionLeft) {
            width = arena.getWidth() - 1;
            height = height - 1;
            nextPositionLeft = true;
            position = getNewPosition(width, height);
            return position;
        }
        if (nextPositionLeft) {
            position = PositionFactory.getNewPosition(position, Direction.LEFT);
            return position;
        }
        position = getNewPosition(position, Direction.RIGHT);
        return position;
    }
}
